import React, { useEffect, useRef, useState } from 'react'
import {  Link, router } from 'expo-router';
import {
    outlineGlyphMap,
    OutlineGlyphMapType,
} from '@ant-design/icons-react-native/lib/outline'
import { Icon, } from '@ant-design/react-native'
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Dimensions,
    Image,
    Button,
    Pressable,
    FlatList,
    TouchableOpacity
} from 'react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
import axios from 'axios';

export default function Search() {


    const [searchTerm, setSearchTerm] = useState('');
    const [history, setHistory] = useState<string[]>([]);

    useEffect(() => {
        // 在组件加载时从 AsyncStorage 读取历史记录
        loadHistory();
    }, []);

    useEffect(() => {
        // 每当历史记录发生变化时，将其保存到 AsyncStorage
        saveHistory();
    }, [history]);

    const loadHistory = async () => {
        try {
            const savedHistory = await AsyncStorage.getItem('searchHistory');
            if (savedHistory) {
                setHistory(JSON.parse(savedHistory));
            }
        } catch (error) {
            console.error('Error loading history:', error);
        }
    };

    const saveHistory = async () => {
        try {
            await AsyncStorage.setItem('searchHistory', JSON.stringify(history));
        } catch (error) {
            console.error('Error saving history:', error);
        }
    };

    const handleSearch = () => {

        if (searchTerm.trim() == '') {
            console.log('请输入');
        }
        else {
            let a: string[] = [...history]
            if (a.length > 0) {
                a.unshift(searchTerm)
            } else {
                a.unshift(searchTerm)
            }
            setHistory([...a])
        }
        AsyncStorage.setItem('searchtext', JSON.stringify(searchTerm));
        router.push('/HomeModel/Results');
        setSearchTerm('');

    };

    const handlehisbut = (item: any) => {
        AsyncStorage.setItem('searchtext', JSON.stringify(item));
        router.push('/HomeModel/Results');
    };

    const clearHistory = () => {
        setHistory([]);
    };

    const renderItem = (item: any) => (
        <View style={styles.historyItem}>
            <Text>{item}</Text>
        </View>
    );



    return (
        <View style={{ height: "100%", backgroundColor: "#faffef" }}>
            <View style={styles.Input}>
                <Pressable onPress={() => router.back()}>
                    <Image source={require("@/assets/img/左箭头.png")} />
                </Pressable>
                <TextInput
                    style={styles.search}
                    placeholder='精选天然水果'
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.nativeEvent.text)}
                    inlineImageLeft='search_icon'
                />
                <View style={{ backgroundColor: "#fff", borderRadius: 100 }}>
                    <Text
                        style={{ paddingHorizontal: 10, paddingVertical: 5, }}
                        onPress={() => (handleSearch())}
                    >搜索</Text>
                </View>
            </View>

            {
                history.length > 0 && (
                    <View style={styles.historys}>
                        <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
                            <Text>历史记录</Text><Text onPress={() => (clearHistory())}>清除记录</Text>
                        </View>
                        <View style={styles.historybox}>
                            {
                                history.map((item: any) => (
                                    <Pressable key={item} onPress={() => (handlehisbut(item))}>
                                        <Text
                                            style={{
                                                backgroundColor: "#f2f2f2", paddingHorizontal: 10,
                                                paddingVertical: 3, fontSize: 12, borderRadius: 50,
                                                margin: 5
                                            }}

                                        >{item}</Text>
                                    </Pressable>
                                ))
                            }
                        </View>
                    </View>
                )
            }



        </View>
    )
}

const styles = StyleSheet.create({
    Input: {
        height: 60,
        backgroundColor: "#99cc33",
        position: "relative",
        display: "flex",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-evenly",
        // alignItems:"flex-start",
        zIndex: 999
    },
    search: {
        width: Dimensions.get('window').width - Dimensions.get('window').width / 2.5,
        borderWidth: 0,
        paddingHorizontal: 15,
        paddingVertical: 5,
        borderRadius: 50,
        backgroundColor: '#fff',
    },
    historys: {
        backgroundColor: "#ffffff",
        padding: 10,
        marginTop: 20,
        borderRadius: 10,
        width: "90%",
        alignSelf: "center",
        marginBottom: 50
    },
    historyItem: {
        padding: 12,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    historyList: {
        flexGrow: 1,
    },
    clearButton: {
        marginTop: 16,
        padding: 12,
        backgroundColor: '#FF4136',
        borderRadius: 5,
    },
    clearButtonText: {
        color: 'white',
        textAlign: 'center',
    },
    historybox: {
        display: "flex",
        flexDirection: "row",
        flexWrap: "wrap",
        marginTop: 10
    }
})